package com.tuling.JUC;

/**
 * @Type JUCLockUtil.java
 * @Desc 生产者消费者
 * @Author wzw
 * @Date 2024/9/10 10:54
 */

//使用if wait 后会出现虚假唤醒的问题
//解决方式使用while wait 方式解决
public class JUCLockSychnizedUtil {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"A").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.decreace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"B").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"C").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.decreace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"D").start();
    }

}

class Data{
    private  int num = 0;

    public synchronized void increment() throws InterruptedException {
        while (num != 0){
            this.wait();
        }
        num ++;
        System.out.println(Thread.currentThread().getName() +"==>" + num);
        this.notifyAll();
    }

    public synchronized void decreace() throws InterruptedException {
        while (num == 0){
            this.wait();
        }
        num --;
        System.out.println(Thread.currentThread().getName() +"==>" + num);
        this.notifyAll();
    }
}
